package com.yeung.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BookShopDaoImp implements BookShopDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int findBookPriceByIsbn(int isbn) {
        String sql = "select price from book where isbn=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, isbn);

    }

    @Override
    public void updateBookStock(int isbn) throws Exception {
        //检查书的库存是否足够
        int stock = findBookStock(isbn);
        String sql = "update book_stock set stock=stock -1 where isbn=?";
        if (stock > 0)
            jdbcTemplate.update(sql, isbn);
        else throw new Exception("库存不足");
    }

    @Override
    public void updateUserAccount(String userName, int price) {
        int balance = findBalance(userName);
        String sql = "update account set balance=balance - ? where userName=?";

        if (balance == 0 || balance < price) try {
            throw new UserAccountException("余额不足");
        } catch (UserAccountException e) {

        }
        else
            jdbcTemplate.update(sql, price, userName);
    }

    @Override
    public int findBookStock(int isbn) {
        String sql = "select stock from book where isbn=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
    }

    @Override
    public int findBalance(String userName) {
        String sql = "select balance from account where userName=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, userName);
    }
}
